# -*- coding:utf-8 -*-
from tkinter import *
from tkinter import ttk
from tkinter.ttk import *
import tkinter.messagebox
import tkinter as tk
from tkinter import filedialog
from media import basic
import os
import subprocess
import re
from media import mediaUtil
import time
import threading
from ui.videoTSPFrame import vtFrame
from ui.videoVNFrame import vnFarame
from ui.videoANFrame import anFrame
from ui.videoCUTFrame import cutFrame
from ui.audioCUTFrame import acutFrame

class mainFrame(object):
    def __init__(self):
        self.root = tkinter.Tk()
        self.root.title('音视频工具')
        self.root.resizable(False, False)
        self.root.minsize(650, 420)
        self.centerWin(self.root,650, 420)
            
        '''菜单初始化'''
        self.menubar = Menu(self.root)
        videoMenu = Menu(self.menubar,tearoff=0)
        videoMenu.add_command(label='音频提取',command=self.openVnFrame)
        videoMenu.add_command(label='视频提取',command=self.openAnFrame)
        videoMenu.add_command(label='视频截取',command=self.openCutFrame)
        videoMenu.add_separator()
        videoMenu.add_command(label='画面旋转',command=self.openVideoTransposeWin)
        self.menubar.add_cascade(label ="视频工具", menu=videoMenu)
        audioMenu = Menu(self.menubar,tearoff=0)
        audioMenu.add_command(label='音频截取',command=self.openAudioCutFrame)
        self.menubar.add_cascade(label ="音频工具", menu=audioMenu)
        self.root['menu'] = self.menubar
        
        tabControl = ttk.Notebook(self.root,width=640,height=350)
        video_tab = ttk.Frame(tabControl)
        tabControl.add(video_tab, text='视频转换')
        audio_tab = ttk.Frame(tabControl)
        tabControl.add(audio_tab, text='音频转换')
        message_tab = ttk.Frame(tabControl)
        tabControl.add(message_tab, text='消息')
        tabControl.grid(row=0,column=0,padx=3,pady=5,sticky=(N, W, E, S))
        
        videoFrame = ttk.Frame(video_tab)
        bm = PhotoImage(file = mediaUtil.SOURCE_PATH+'medien.png')
        tipLabel = Label(videoFrame,image=bm)
        tipLabel.bm = bm
        tipLabel.grid(row=0,column=0,padx=5,pady=5,sticky=(N, W, E, S))
        
        self.outType = ttk.Combobox(videoFrame,width=10, textvariable=StringVar())  
        self.outType["values"] = basic.VIDEOS
        self.outType["state"] = "readonly"
        self.outType.current(0)
        self.outType.grid(row=0,column=2,padx=5,pady=5)
        addFileBtn = ttk.Button(videoFrame,text="添加文件",width=5,command=self.getFilePath).grid(row=0,column=3,sticky=W+E,padx=10)

        
        '''待转换视频列表'''
        self.videoTree=ttk.Treeview(videoFrame,show="headings",displaycolumns=['NAME','URL','TYPE','LONG','SIZE','ST'],columns=('ID','NAME','URL','TYPE','LONG','SIZE','BITRATE','ST'),height=10)
        self.videoTree.grid(column=0,columnspan=4, row=1,padx=3,pady=5,sticky=(N, W, E, S))
        self.videoTree.heading('NAME', text='名称')
        self.videoTree.heading('URL', text='路径')
        self.videoTree.heading('TYPE', text='类型')
        self.videoTree.heading('LONG', text='时长')
        self.videoTree.heading('SIZE', text='大小（MB）')
        self.videoTree.heading('ST', text='状态')
        self.videoTree.column('NAME', width=150, anchor='w')
        self.videoTree.column('URL', width=100, anchor='w')
        self.videoTree.column('TYPE', width=100, anchor='center')
        self.videoTree.column('LONG', width=100, anchor='center')
        self.videoTree.column('SIZE', width=100, anchor='center')
        self.videoTree.column('BITRATE', width=100, anchor='center')
        self.videoTree.column('ST', width=70, anchor='center')
        
        outLabel = Label(videoFrame,text='输出至文件夹：')
        outLabel.grid(column=0, row=2,padx=3,sticky=(N, W, E, S))
        self.outString = StringVar()
        self.outPath = Entry(videoFrame,textvariable = self.outString,width=40,state=DISABLED)
        self.outPath.grid(column=1, row=2,padx=3,sticky=(N, W, E, S))
        pathBtn = ttk.Button(videoFrame,text="添加文件夹",width=5,command=self.getVideoOutPath).grid(row=2,column=2,sticky=W+E,padx=10)
        convertBtn = ttk.Button(videoFrame,text="转换",width=5,command=self.videoConvert).grid(row=2,column=3,sticky=W+E,padx=10)

        videoFrame.grid(row=0,column=0,padx=5,pady=5,sticky=(N, W, E, S))
        
        audioFrame = ttk.Frame(audio_tab)
        audioBm = PhotoImage(file = mediaUtil.SOURCE_PATH+'music.png')
        audioLabel = Label(audioFrame,image=audioBm)
        audioLabel.bm = audioBm
        audioLabel.grid(row=0,column=0,padx=5,pady=5,sticky=(N, W, E, S))
        
        self.audioType = ttk.Combobox(audioFrame,width=10, textvariable=StringVar())  
        self.audioType["values"] = basic.AUDIOS
        self.audioType["state"] = "readonly"
        self.audioType.current(0)
        self.audioType.grid(row=0,column=2,padx=5,pady=5)
        addAudioFileBtn = ttk.Button(audioFrame,text="添加文件",width=5,command=self.getAudioPath).grid(row=0,column=3,sticky=W+E,padx=10)

        
        self.audioTree=ttk.Treeview(audioFrame,show="headings",displaycolumns=['NAME','URL','TYPE','LONG','SIZE','ST'],columns=('ID','NAME','URL','TYPE','LONG','SIZE','ST'),height=10)
        self.audioTree.grid(column=0,columnspan=4, row=1,padx=3,pady=5,sticky=(N, W, E, S))
        self.audioTree.heading('NAME', text='名称')
        self.audioTree.heading('URL', text='路径')
        self.audioTree.heading('TYPE', text='类型')
        self.audioTree.heading('LONG', text='时长')
        self.audioTree.heading('SIZE', text='大小（MB）')
        self.audioTree.heading('ST', text='状态')
        self.audioTree.column('NAME', width=150, anchor='w')
        self.audioTree.column('URL', width=100, anchor='w')
        self.audioTree.column('TYPE', width=100, anchor='center')
        self.audioTree.column('LONG', width=100, anchor='center')
        self.audioTree.column('SIZE', width=100, anchor='center')
        self.audioTree.column('ST', width=70, anchor='center')
        
        outAduioLabel = Label(audioFrame,text='输出至文件夹：')
        outAduioLabel.grid(column=0, row=2,padx=3,sticky=(N, W, E, S))
        self.outAudioString = StringVar()
        self.outAudioPath = Entry(audioFrame,textvariable = self.outAudioString,width=40,state=DISABLED)
        self.outAudioPath.grid(column=1, row=2,padx=3,sticky=(N, W, E, S))
        audioPathBtn = ttk.Button(audioFrame,text="添加文件夹",width=5,command=self.getAudioOutPath).grid(row=2,column=2,sticky=W+E,padx=10)
        auidoConvertBtn = ttk.Button(audioFrame,text="转换",width=5,command=self.audioConvert).grid(row=2,column=3,sticky=W+E,padx=10)

        audioFrame.grid(row=0,column=0,padx=5,pady=5,sticky=(N, W, E, S))
        
        messageFrame = ttk.Frame(message_tab)
        msg_text = Text(messageFrame,width=90,height=26)
        msg_text.config(state=DISABLED)
        msg_text.grid(row=0,column=0,padx=0,pady=0,sticky=(N, W, E, S))
        messageFrame.grid(row=0,column=0,padx=5,pady=5,sticky=(N, W, E, S))
        
        '''状态栏'''
        '''
        statusBarFrame = ttk.Frame(self)
        statusBarFrame.grid(row=1,column=0,padx=3,sticky=(N, W, E, S))
        
        label = Label(statusBarFrame,text='当前视频转换进度：',relief=SOLID)
        label.grid(row=0,column=0,padx=3,sticky=(N, W, E, S))
        '''
    '''
    视频画面翻转
    '''
    def openVideoTransposeWin(self):
        '''
        self.vtWin = tkinter.Toplevel(self.root)
        self.vtWin.title("视频画面翻转")
        #子窗口随着主窗口关闭或最小化
        self.vtWin.transient(self.root)
        #窗口不能改变大小
        self.vtWin.resizable(False, False)
        self.vtWin.minsize(260, 130)
        #窗口居中
        self.centerWin(self.vtWin,260, 130)
        '''
        vtf = vtFrame(self.root)
    
    '''打开从视频中提取音频窗口'''    
    def openVnFrame(self):
        vnf = vnFarame(self.root)
        
    
    '''打开从视频中提取视频窗口'''
    def openAnFrame(self):
        anf = anFrame(self.root)
        
    '''打开视频截取窗口'''
    def openCutFrame(self):
        cutf = cutFrame(self.root)
        
    '''打开音频截取窗口'''
    def openAudioCutFrame(self):
        acutf = acutFrame(self.root)
        
        
    '''窗口居中'''
    def centerWin(self,root,width,height):
        screenwidth = root.winfo_screenwidth()
        screenheight = root.winfo_screenheight()
        size = '%dx%d+%d+%d' % (width, height, (screenwidth - width)/2, (screenheight - height)/2)  
        root.geometry(size)
    
    '''视频选取输出文件夹'''
    def getVideoOutPath(self):
        path_ = filedialog.askdirectory()
        self.outString.set(path_)
    
    '''音频选择输出文件夹'''   
    def getAudioOutPath(self):
        path_ = filedialog.askdirectory()
        self.outAudioString.set(path_)
    
    '''添加要转换的文件'''
    def getFilePath(self):
        '''清空待转换的视频列表'''
        items = self.videoTree.get_children()
        for item in items:
            self.videoTree.delete(item)
            
        paths = filedialog.askopenfilenames()
        index = 0
        for path in paths:
            #获取文件扩展名
            ext = os.path.splitext(path)[1][1:]
            for type in basic.VIDEOS:
                if type == ext :
                    cmd = mediaUtil.cmd_mediaInfo(path)
                    subprocess.call(cmd)
                    result = subprocess.getoutput(cmd)
                    b = re.search(r'bitrate: (\d+) kb', result)
                    #获取原视频的比特率
                    bitrate = b.group(1)
                    #视频文件时长
                    d = re.search(r'Duration: (\d+):(\d+):(\d+).(\d+),', result)
                    duration= '{0}:{1}:{2}'.format(d.group(1),d.group(2),d.group(3))
                    
                    #duration = re.search('Duration: ',result).span()
                    #视频文件时长
                    #duration = result[duration[1]:duration[1]+8]
                    #视频文件名称
                    videoName = os.path.basename(path)
                    #视频文件大小
                    videoSize = os.path.getsize(path)
                    #从表格末尾插入数据
                    self.videoTree.insert('',END,values=(index,videoName,path,ext,duration,format(videoSize/1024/1024,'.2f'),bitrate,'待转换'))
                    self.videoTree.update()
                    index+=1
    '''添加音频文件'''                
    def getAudioPath(self):
        '''清空待转换的视频列表'''
        items = self.audioTree.get_children()
        for item in items:
            self.audioTree.delete(item)
        paths = filedialog.askopenfilenames()
        index = 0
        for path in paths:
            #获取音频文件扩展名
            ext = os.path.splitext(path)[1][1:]
            for type in basic.AUDIOS:
                if type == ext :
                    cmd = mediaUtil.cmd_mediaInfo(path)
                    subprocess.call(cmd)
                    rst = subprocess.getoutput(cmd)
                    duration = re.search('Duration: ',rst).span()
                    #视频文件时长
                    duration = rst[duration[1]:duration[1]+8]
                    #视频文件名称
                    audioName = os.path.basename(path)
                    #视频文件大小
                    audioSize = os.path.getsize(path)
                    #从表格末尾插入数据
                    self.audioTree.insert('',END,values=(index,audioName,path,ext,duration,format(audioSize/1024/1024,'.2f'),'待转换'))
                    self.audioTree.update()
                    index+=1
    
    '''视频转换进度'''
    def getVideoProgress(self,old_second,cmd,item):
        iscomplete = 0
        while iscomplete ==0:
            info = mediaUtil.getCmdExecInfo(cmd)
            if info !="":
                iscomplete=1
        values = self.videoTree.item(item, "values")
        v = list(values)
        v[7] = '已转换'
        values = tuple(v)
        self.videoTree.item(item, values=values)
        self.videoTree.update()
    
    '''音频转换进度'''
    def getAudioProgress(self,old_second,cmd,item):
        iscomplete = 0
        while iscomplete ==0:
            info = mediaUtil.getCmdExecInfo(cmd)
            if info !="":
                iscomplete=1
        values = self.audioTree.item(item, "values")
        v = list(values)
        v[6] = '已转换'
        values = tuple(v)
        self.audioTree.item(item, values=values)
        self.audioTree.update()
    
    '''
            开始转换视频
    '''                
    def videoConvert(self):
        #转换的目标格式
        ext = self.outType.get()
        if ext =="":
            tkinter.messagebox.showerror("提示","请选择视频转换的目标格式")
            return False
        #转出的文件夹路径
        outPath = self.outPath.get()
        if outPath =="":
            tkinter.messagebox.showerror("提示","请选择视频转换输出文件夹")
            return False
        items = self.videoTree.get_children()
        for item in items:
            values = self.videoTree.item(item, "values")
            if values[7] =="待转换" and ext != values[3]:
                #获取视频文件名称
                videoName = os.path.basename(values[2])
                ret = list(re.finditer('\.', videoName))
                videoName = videoName[0:ret[-1].span()[0]]
                inputFile = values[2]
                outputFile = outPath+'/{0}.{1}'.format(videoName,ext)
                cmd = mediaUtil.cmd_videoSimpleConvert(inputFile, outputFile,int(values[6]))
                if cmd == None:
                    tkinter.messagebox.showerror("提示","获取转换命令失败")
                old_second = mediaUtil.getSecond(values[4])
                
                v = list(values)
                v[7] ='转换中'
                values = tuple(v)
                self.videoTree.item(item, values=values)
                self.videoTree.update()
                #调用转换视频的命令
                subprocess.Popen(cmd)
                video_thread = threading.Thread(target=self.getVideoProgress,args=(old_second,cmd,item))
                video_thread.start()
    
    '''开始转换音频格式'''
    def audioConvert(self):
        try:
            #转换的目标格式
            ext = self.audioType.get()
            if ext =="":
                tkinter.messagebox.showerror("提示","请选择音频转换的目标格式")
                return False
            #转出的文件夹路径
            outPath = self.outAudioPath.get()
            if outPath =="":
                tkinter.messagebox.showerror("提示","请选择音频转换输出文件夹")
                return False
            items = self.audioTree.get_children()
            for item in items:
                values = self.audioTree.item(item, "values")
                if values[6] =="待转换" and ext != values[3]:
                    #获取视频文件名称
                    audioName = os.path.basename(values[2])
                    ret = list(re.finditer('\.', audioName))
                    audioName = audioName[0:ret[-1].span()[0]]
                    inputFile = values[2]
                    outputFile = outPath+'/{0}.{1}'.format(audioName,ext)
                    cmd = mediaUtil.cmd_audioConvert(inputFile, outputFile,ext)
                    if cmd == None:
                        tkinter.messagebox.showerror("提示","获取转换命令失败")
                    old_second = mediaUtil.getSecond(values[4])
                    
                    v = list(values)
                    v[6] ='转换中'
                    values = tuple(v)
                    self.audioTree.item(item, values=values)
                    self.audioTree.update()
                    #调用转换视频的命令
                    subprocess.Popen(cmd)
                    video_thread = threading.Thread(target=self.getAudioProgress,args=(old_second,cmd,item))
                    video_thread.start()
        except:
            print(sys.exc_info())